package com.baimo.controller.admin;

import com.baimo.pojo.User;
import com.baimo.service.UserService;
import com.baimo.tool.IPUtils;
import com.baimo.tool.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author 白墨
 * @ClassName UserController.java
 * @Description 用户类控制层
 * @createTime 2021/4/18 23:24:50
 */
@Controller
@RequestMapping("/admin")
public class UserController {

//    @Resource
    @Autowired
    private UserService userService;
    /**
    * Description: 进入登录页
    * @author BaiMo
    * @date 2021/4/19 0:05:09
    * @return 登录页
    */
    @GetMapping()
    public  String loginPage(){
        return "admin/login";
    }

    /**
     * @description 登录功能
     * @author 白墨
     * @param model 模型
     * @param user 用户
     * @param session 众所周知
     * @param attributes 抓发属性
     * @param request 请求
     * @updateTime 2021/4/26 23:21:39
     * @return java.lang.String
     */
    @PostMapping("/login")
    public String login(Model model,User user, HttpSession session, RedirectAttributes attributes, HttpServletRequest request){
        user.setPassword(MD5Utils.code(user.getPassword()));
        user.setLoginIP(IPUtils.getIpAddr(request));
        user.setLoginTime(new Date());
        User loginUser= userService.login(user);
        if (loginUser!=null){
            loginUser.setPassword(null);
            model.addAttribute("loginTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(loginUser.getLoginTime()));
            session.setAttribute("user",loginUser);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名或密码错误");
            return"redirect:/admin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
